var app = require('../app.js');
var httpServer = app.get('http');
var wss = require('socket.io')(httpServer);
var _ = require('lodash');
var log = console.log.bind(console);

var roomList = [];
/**
 * 连接时
 */
wss.on('connection',(skt)=>{
    var room = {};
    var man = {};
    skt.on('JOIN_ROOM',function(msg,cb){
        if(!msg.userName || !msg.roomName)
            cb && cb({info:'名称和房间不能不填'});
        else {
            //增加新的房间
            room = _.find(roomList,{name:msg.roomName}) || (roomList.push({ name:msg.roomName,userList:[] }) && _.last(roomList));
            if(_.find(room.userList,{name:msg.userName}))
                cb && cb({info:'哟,好巧哦,这个名字似曾相识啊!'});
            else{
                //增加新成员
                man = {
                    name: msg.userName,
                    portrait: msg.portrait,
                    token: skt.id,
                    socket: skt
                }
                var friends = _.map(room.userList,_.partial(_.pick,_,['name','token','portrait']));
                cb && cb(null,{roomName:msg.roomName,userName:msg.userName,portrait:msg.portrait,token:skt.id,friends:friends});
                //通知房间的其他人
                _.each(room.userList,f=> f.socket && f.socket.emit('JOIN_ROOM',{name:man.name,portrait:msg.portrait}))
                //加入房间
                room.userList.push(man);
                log('JOIN_ROOM:',msg);
            }
        }
    });
    skt.on('ICE',function(msg){
        var friend = _.find(room.userList,{name:msg.to});
        friend && friend.socket && friend.socket.emit('ICE',{from:man.name,type:msg.type,ice:msg.ice});
        log('ICE:',msg);
    });
    skt.on('OFFER',(msg)=>{
        var friend = _.find(room.userList,{name:msg.to});
        friend && friend.socket && friend.socket.emit('OFFER',{from:man.name,dsp:msg.dsp});
        log('OFFER:',msg);
    });
    skt.on('ANSWER',(msg)=>{
        var friend = _.find(room.userList,{name:msg.to});
        friend && friend.socket && friend.socket.emit('ANSWER',{from:man.name,dsp:msg.dsp});
        log('ANSWER:',msg);
    });
    skt.on('disconnect', function () {
        _.remove(room.userList,_.iteratee({token:man.token}))
        //下线时通知其他人
        _.each(room.userList,f=> f.socket && f.socket.emit('LEAVE_ROOM',{name:man.name}));
        log('LEAVE_ROOM:',man.name);
    });
});
